import {
  AreaCodeItem,
  AreaCodeKey,
  CacheAreaCode,
  Lang,
  MAXAGE,
  STOREKEY,
  STOREMAX,
  ZH,
} from "./data";

// 获取选项
export async function getNewOptions(lang: Lang) {
  let cacheCode: AreaCodeItem[] = [];
  // 取缓存
  try {
    const cache = JSON.parse(
      localStorage.getItem("areaCode") || "{}"
    ) as CacheAreaCode;
    // 验证过期时间
    const { timestamp, list } = cache;
    const oldTime = Number(timestamp);
    if (timestamp && list) {
      // 是否过期
      const isExpire = Date.now() - oldTime > MAXAGE;
      !isExpire && (cacheCode = list);
    }
  } catch {}
  // 请求
  if (!cacheCode.length) {
    try {
      const dataList = await getAreaCodes() as AreaCodeItem[];
      if (dataList.length) {
        cacheCode = dataList;
        const cacheDate: CacheAreaCode = {
          timestamp: String(Date.now()),
          list: dataList,
        };
        localStorage.setItem("areaCode", JSON.stringify(cacheDate));
      }
    } catch {
      console.log("请求区号接口出错");
    }
  }
  paseOptionByLang(cacheCode, lang);
  return cacheCode;
}
// 发请求, 防止并发请求
let fetchLoading = false
const resolveCatch:((s:any) => void)[] = []
export async function getAreaCodes() {
  return new Promise(async resolve => {
    if (fetchLoading) {
      resolveCatch.push(resolve)
      return
    }
    fetchLoading = true
    try {
      const res = await fetch("/portal/main/getAreaCodeList", {
        method: "POST",
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
        },
        body: JSON.stringify({
          // 是否排序(是: +86在前面, 后续根据sortByLanguage 进行A-Z的排序; 否: 将默认排序给出)
          isSort: true,
          // 排序依据: zh; en
          sortByLanguage: "zh",
        }),
      })
        .then(
          (res) => res.json(),
          (err) => {
            console.log("请求错误", err);
            return [];
          }
        )
        .then((data) => {
          return data.data;
        });
      // 接口结果不可信，再进一步判断
      const realList = (res.length ? res : [1]) as AreaCodeItem[]
      resolve(realList)
      resolveCatch.forEach(v => v(realList))
      // return (res.length ? res : []) as AreaCodeItem[];
    } catch {
      const nullList = [] as AreaCodeItem[];
      resolve(nullList)
      resolveCatch.forEach(v => v(nullList))
    }
    // 完成请求后清空状态
    resolveCatch.length = 0
    fetchLoading = false
  })
  
}

// 处理语言环境选项
export function paseOptionByLang(originCode: AreaCodeItem[], lang: Lang) {
  originCode.forEach((a) => {
    const { zhName, enName, areaCodeForPlusSign } = a;
    // 兼容+86和++86
    a.areaCodeForPlusSign = areaCodeForPlusSign.replace("++", "+");
    const label =
      (lang !== ZH ? enName : zhName) + ` (${a.areaCodeForPlusSign})`;
    a.label = label;
  });
}

// 存常用
export function setUsed(code: string) {
  const list = getUsed();
  // 对于大于3个的情况
  if (!list.includes(code)) {
    list.push(code);
    localStorage.setItem(STOREKEY, JSON.stringify(list.slice(-STOREMAX)));
  } else {
  }
}
// 取常用
export function getUsed() {
  const usedList = localStorage.getItem(STOREKEY) || "[]";
  let res: string[] = [];
  try {
    const list = JSON.parse(usedList);
    if (Array.isArray(list)) {
      if (list.find((v) => typeof v !== "string")) {
        // 内容被篡改成其他类型
        res = [];
      } else {
        res = list;
      }
    }
  } catch {
    console.log(`localStorage的 ${STOREKEY} 解析格式错误`);
  }
  return res;
}
/**
 * 通过key-value形式查询原始数据
 */
export function findData(
  originCode: AreaCodeItem[],
  key: AreaCodeKey,
  value: string
) {
  return originCode.filter((a) => a[key] === value);
}

// 处理常用数据，把常用和中国区号放前面
export function parseUsed(originCode: AreaCodeItem[]) {
  originCode.forEach((v) => (v.isUsed = false));
  const usedList = getUsed();
  if (!usedList.find((v) => v === ZH)) {
    usedList.push(ZH);
  }
  const usedArea = [];
  for (let i = 0; i < usedList.length; i++) {
    const idx = originCode.findIndex((v) => v.simpleCode === usedList[i]);
    if (idx !== -1) {
      const usedDate = originCode.splice(idx, 1);
      // 中国区号不在前三就不添加为常用
      i < 3 && (usedDate[0].isUsed = true);
      usedArea.push(usedDate[0]);
    }
  }

  originCode.unshift(...usedArea);
}

/**
 * 处理区号统一格式为 +code 这样的形式
 * @param code 区号
 * @returns  +code
 */
export function parseCode(code: string) {
  if (!code) return "+86";
  let ln = 0;
  let resStr = "";
  while (ln < code.length) {
    if (!Number.isNaN(Number(code[ln]))) {
      resStr += code[ln];
    }
    ln++;
  }

  return "+" + String(Number(resStr));
}

/**
 * 深拷贝区号，预防同页面需要多个语言环境
 * @param areaCodes 
 * @returns AreaCodeItem[]
 */
export const cloneAreaCode = (areaCodes:AreaCodeItem[]) => {
  return areaCodes.map(v => {
    return {
      ...v
    }
  })
}

type ChoseConf = {
  filedLabel: AreaCodeKey | null
  parseLabel: ((a:AreaCodeItem) => string) | null
}
// 计算显示的字段
export const parseShowLabel = (area:AreaCodeItem, conf: ChoseConf) => {
  const { label } = area
  const { filedLabel, parseLabel } = conf
  let res = label
  if (filedLabel) {
    const fied = area[filedLabel]
    fied && (res = String(fied))
  } 
  if (typeof parseLabel === 'function') {
    res = parseLabel(area)
  }
  return res
}

// 根据语言排序处理
export const sortCode = (arr:AreaCodeItem[], lang:Lang) => {
  if (lang !== ZH) {
    // 英文按首字母排序
    arr.sort((a,b) => {
      const codeA = a.simpleCode.toLowerCase();
      const codeB = b.simpleCode.toLowerCase();
      return codeA < codeB ? -1 : 1
    })
  }
}